<template>
    <div class="pageCon">
        <div style="display: flex; align-items: center; margin-bottom: 20px;height: 40px;width: 100%;">
            <el-button @click="editUser()">新增用户</el-button>
            <el-input v-model="searchName" placeholder="请输入搜索姓名" style="width: 200px; margin-left:20px" />
            <el-button @click="searchUser" type='primary'>搜索</el-button>
            <el-upload :headers="uploadHeader" action="http://localhost:8080/apis/uploadXlsxUsers"
                :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" accept=".xlsx"
                style="margin-left: 20px;margin-top: 10px;">
                <el-button type="primary">批量导入用户信息</el-button>
            </el-upload>
            <el-button @click="downloadExample">下载xlsx示例</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="jobNumber" label="工号" width="180" />
            <el-table-column prop="username" label="账号" width="180" />
            <el-table-column prop="name" label="姓名" width="180" />
            <el-table-column prop="role" label="权限" width="180" />
            <el-table-column prop="password" label="密码" width="180">
                <template #default="{ row }">
                    <el-button @click="row.showPassword = !row.showPassword">{{ row.showPassword ? row.password : '*' }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="primary" @click="editUser(row)">编辑</el-button>
                    <el-button type="danger" @click="deleteUser(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="display: flex; align-items: center;margin-top: 20px;gap: 10px;">
            <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
                @current-change="handleCurrentChange" />
            用户总计{{ total }}人
        </div>

        <el-dialog title="编辑用户" v-model="userWindow" destroy-on-close>
            <el-form>
                <el-form-item label="账号">
                    <el-input v-model="username" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input type="password" v-model="password" />
                </el-form-item>
                <el-form-item label="工号">
                    <el-input v-model="jobNumber" />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="name" />
                </el-form-item>
                <el-form-item label="权限">
                    <el-select v-model="role">
                        <el-option label="管理员" value="admin" />
                        <el-option label="普通用户" value="user" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm()">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Api } from '@/api/index.js'
import { useUserStore } from '@/stores'
import * as XLSX from 'xlsx'
const useUser = useUserStore()
const userWindow = ref(false)
const searchName = ref('')
const username = ref('')
const password = ref('')
const jobNumber = ref('')
const name = ref('')
const role = ref('')
const tableData = ref([])
const page = ref(1)
const pageSize = ref(30)
const total = ref(0)
const mode = ref('')
const uploadHeader = ref({
    Authorization: 'Bearer ' + useUser.token
})

const searchUser = () => {
    Api.getAllUsers({
        page: page.value,
        pageSize: pageSize.value,
        name: searchName.value
    }).then((res) => {
        tableData.value = res.users
        total.value = res.total
    }).catch((err) => {
        ElMessage.error(err.response.data.message)
    })
}
const downloadExample = () => {
    const worksheet = XLSX.utils.json_to_sheet([]);
    const workbook = XLSX.utils.book_new();
    // 设置表头
    XLSX.utils.sheet_add_aoa(worksheet, [["jobNumber", "username", "name", "role", 'password']], { origin: "A1" });
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    XLSX.writeFile(workbook, `用户列表实例.xlsx`);
}
const submitForm = () => {
    if (username.value === '') {
        ElMessage.error('请输入账号')
        return
    }
    if (password.value === '') {
        ElMessage.error('请输入密码')
        return
    }
    if (jobNumber.value === '') {
        ElMessage.error('请输入工号')
        return
    }
    if (name.value === '') {
        ElMessage.error('请输入姓名')
        return
    }
    if (role.value === '') {
        ElMessage.error('请选择权限')
        return
    }

    if (mode.value) {
        Api.updateUser({
            id: mode.value,
            username: username.value,
            password: password.value,
            jobNumber: jobNumber.value,
            name: name.value,
            role: role.value
        }).then((res) => {
            ElMessage.success('编辑成功')
            userWindow.value = false
            getAllUsers()
        }).catch((err) => {
            ElMessage.error(err.response.data.message)
        })
    } else {
        Api.register({
            username: username.value,
            password: password.value,
            jobNumber: jobNumber.value,
            name: name.value,
            role: role.value
        }).then((res) => {
            ElMessage.success('新增成功')
            userWindow.value = false
            getAllUsers()
        }).catch((err) => {
            ElMessage.error(err.response.data.message)
        })
    }
}

const getAllUsers = () => {
    Api.getAllUsers({
        page: page.value,
        pageSize: pageSize.value,
        name: searchName.value,
        jobNumber: searchName.value,
        username: searchName.value
    }).then((res) => {
        tableData.value = res.users
        total.value = res.total
    }).catch((err) => {
        ElMessage.error(err.response.data.message)
    })
}

const editUser = (row) => {
    userWindow.value = true
    mode.value = row.id || ''
    username.value = row.username
    password.value = row.password
    jobNumber.value = row.jobNumber
    name.value = row.name
    role.value = row.role
}

const handleCurrentChange = (val) => {
    page.value = val
    getAllUsers()
}

const deleteUser = (id) => {
    Api.deleteUser({ id }).then((res) => {
        ElMessage.success('删除成功')
        getAllUsers()
    }).catch((err) => {
        ElMessage.error(err.response.data.message)
    })
}

const beforeUpload = (file) => {
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isExcel) {
        ElMessage.error('只能上传 Excel 文件!');
        return false;
    }
    return true;
};

const handleSuccess = (res) => {
    if (res.status === 200) {
        ElMessage.success('导入成功')
        getAllUsers()
    } else {
        ElMessage.error(res.message)
    }
};

const handleError = (err) => {
    ElMessage.error('导入失败: ' + JSON.parse(err.message).message);
};

onMounted(() => {
    getAllUsers()
})
</script>

<style lang="scss" scoped>
.pageCon {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
</style>